package code.example.base.util.concurrent.lock.speed;


import code.example.base.util.concurrent.lock.Counter;
import code.example.tool.FixedThreadPool;

import java.util.concurrent.TimeUnit;

public abstract class SpeedTest {

    public void test(int threadNum,Runnable runnable){
        FixedThreadPool threadPool = new FixedThreadPool(threadNum);
        long startTime = System.currentTimeMillis();
        for(int i=0;i<threadNum;i++){
            threadPool.execute(runnable);
        }
        threadPool.awaitTermination(100000, TimeUnit.SECONDS);
        long endTime = System.currentTimeMillis();
        System.out.println("use time:"+(endTime - startTime));

    }

    public abstract  void lockRun(SpeedRunnable speedRunnable);

    int number = 0;
    private void watiTime(int count){

        long startTime = System.nanoTime();
        for(int l = 0;l<10;l++){
            int i=0;
            i++;
            number = i+count;
        }
        if(count %10==0){
            System.out.println("wait time:"+(System.nanoTime() - startTime));
        }

    }



    public void testSpeed(int threadNum,int runTimes,final SpeedRunnable speedRunnable){
        final int count =runTimes/threadNum;
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                long startTime = System.currentTimeMillis();
                for(int i=0;i<count;i++){
                    lockRun(speedRunnable);
                try {

                        TimeUnit.MILLISECONDS.sleep(1);

                    }catch (Exception e){}
                }
                long endTime = System.currentTimeMillis();
                System.out.println(Thread.currentThread().getName()+" use time:"+(endTime-startTime));
            }
        };
        test(threadNum, runnable);
    }

    public void startTest(){
        Counter counter = new Counter();
        SpeedRunnable speedRunnable = new SpeedRunnable(counter,waitTime);
        testSpeed(threadNum,runTimes,speedRunnable);
        System.out.println("counter:"+counter.getCount());
    }
    int waitTime = 1;
    int threadNum =256;
    int runTimes = 100000;


}
